<?php
/**
 * ExaminationType Service.
 * User: Administrator
 * Date: 2020/2/13 0013
 * Time: 下午 2:02
 */
namespace app\api\service\questions;

use app\api\model\questions\DoAnswer as DoAnswerModels;

Class DoAnswer {

    /**
     * 获取做过的题目
     *
     * @param int $id
     * @return mixed
     */
    public function doAnswer( int $id )
    {
        return DoAnswerModels::qid($id)->select();
    }

    /**
     * 提交题目
     * @param array $data
     * @return boolean
     */
    public function submission(array $data)
    {
        DoAnswerModels::qid($data['qid'])->delete();
        $save = [];
        foreach ( $data['list'] as $_key => $_list ) {
            foreach ( $_list['answer'] as $_answer ) {
                $save[] = ['qid'=>$data['qid'],'aid'=>$_list['aid'],'oid'=>$_answer['oid'],'correct'=>$_answer['correct']];
            }
        }
        $doAnswerModel = new DoAnswerModels();
        $res = $doAnswerModel->saveAll($save);
        return !$res->isEmpty();
    }

    /**
     * 查询我的错题
     * @return mixed
     */
    public function wrong()
    {
        return DoAnswerModels::useGlobalScope(['uid'])
            ->join('question', 'qid = question.id')
            ->field('count(qid) as errCount,qid,question.title')->where('correct',0)->group('qid')->select();
    }

    /**
     * 查询错误的小题
     * @return mixed
     */
    public function wrongAnswer(int $qid)
    {
        return DoAnswerModels::useGlobalScope(['uid'])
            ->alias('do_answer')
            ->join('answer', 'aid = answer.id')
            ->field('aid,answer.title')
            ->where('do_answer.qid', $qid)->where('correct', 0)->selectOrFail();
    }

}